/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gui.Ventas;

import Atxy2k.CustomTextField.RestrictedTextField;
import javax.swing.JOptionPane;
import javax.swing.table.AbstractTableModel;
import java.util.ArrayList;
import Controlador.Bean.Ventas.PlanVentas;
import Controlador.Service.Ventas.GestionVentas;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.swing.table.TableRowSorter;

/**
 *
 * @author Luis Enrique
 */
public class PlanVentasMainPanel extends javax.swing.JPanel {

    PedidoBusquedaTableModel myTableModel;
    SimpleDateFormat formatFecha = new SimpleDateFormat("dd/MM/yyyy");
    ArrayList<PlanVentas> planes = GestionVentas.getInstance().queryAllPlanes();
    
    class PedidoBusquedaTableModel extends AbstractTableModel{
        String [] titles = {"Núm. de Plan de Ventas","Fecha de Registro","Fecha Inicial","Fecha Final","Estado"};

        @Override
        public int getRowCount() {
            return planes.size();
        }

        @Override
        public int getColumnCount() {
            return titles.length;
        }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            String res=null;
            PlanVentas pv = planes.get(rowIndex);
            switch(columnIndex){
                case 0: res = pv.getNumero()+""; break;
                case 1: res = formatFecha.format(pv.getFechaRegistro());break;
                case 2: res = formatFecha.format(pv.getFechaInicio()); break;
                case 3: res = formatFecha.format(pv.getFechaFin());break;
                case 4: res = pv.getEstado(); break;
            }
            return res;
        }
        
        @Override
        public String getColumnName(int col){
            return titles[col];
        }
    }
    
    public PlanVentasMainPanel() {
        initComponents();      
        
        RestrictedTextField restricted = new RestrictedTextField(txtNumPlan);
        restricted.setLimit(6);
        restricted.setOnlyNums(true);
        
        myTableModel = new PedidoBusquedaTableModel();
        tblPlanes.setModel(myTableModel);
        TableRowSorter<PedidoBusquedaTableModel> sorter = new TableRowSorter<PedidoBusquedaTableModel> ((PedidoBusquedaTableModel) tblPlanes.getModel());
        tblPlanes.setRowSorter(sorter);
    }

    public void refreshItemsTable(){
        this.planes = GestionVentas.getInstance().queryAllPlanes();
        myTableModel.fireTableChanged(null);        
    }
    
    public void refreshItemsTable2(ArrayList<PlanVentas> planesBusq){
        this.planes = new ArrayList(planesBusq);
        myTableModel.fireTableChanged(null);        
    }
        
    public void limpiarCriterios(){
        txtNumPlan.setText("");
        cmbEstado.setSelectedIndex(0);
        dpFechaReg.setDate(null);
        dpFechaI.setDate(null);
        dpFechaF.setDate(null);
    }
       
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        tblPlanes = new javax.swing.JTable();
        jPanel2 = new javax.swing.JPanel();
        jLabel10 = new javax.swing.JLabel();
        txtNumPlan = new javax.swing.JTextField();
        jLabel9 = new javax.swing.JLabel();
        dpFechaReg = new org.jdesktop.swingx.JXDatePicker();
        jLabel8 = new javax.swing.JLabel();
        cmbEstado = new javax.swing.JComboBox();
        jLabel11 = new javax.swing.JLabel();
        dpFechaI = new org.jdesktop.swingx.JXDatePicker();
        jLabel12 = new javax.swing.JLabel();
        dpFechaF = new org.jdesktop.swingx.JXDatePicker();
        btnBuscar = new javax.swing.JButton();
        btnLimpiar = new javax.swing.JButton();
        btnRegistrarEstimado = new javax.swing.JButton();
        btnRegistrarPedidos = new javax.swing.JButton();
        btnAnular = new javax.swing.JButton();

        setMaximumSize(new java.awt.Dimension(784, 549));
        setMinimumSize(new java.awt.Dimension(784, 549));
        setPreferredSize(new java.awt.Dimension(784, 549));

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Lista de Planes de Venta"));
        jPanel1.setToolTipText("");
        jPanel1.setMaximumSize(new java.awt.Dimension(764, 305));
        jPanel1.setMinimumSize(new java.awt.Dimension(764, 305));
        jPanel1.setPreferredSize(new java.awt.Dimension(764, 305));
        jPanel1.setLayout(new java.awt.BorderLayout());

        tblPlanes.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        tblPlanes.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        tblPlanes.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tblPlanesMouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(tblPlanes);

        jPanel1.add(jScrollPane2, java.awt.BorderLayout.CENTER);

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Criterios de Búsqueda"));

        jLabel10.setText("Núm. de Plan de Ventas");

        jLabel9.setText("Fecha de Registro");

        jLabel8.setText("Estado");

        cmbEstado.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Seleccionar", "Registrado", "Procesado" }));

        jLabel11.setText("Fecha Inicial");

        dpFechaI.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                dpFechaIActionPerformed(evt);
            }
        });

        jLabel12.setText("Fecha Final");

        btnBuscar.setText("Buscar");
        btnBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBuscarActionPerformed(evt);
            }
        });

        btnLimpiar.setText("Limpiar");
        btnLimpiar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLimpiarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel10)
                            .addComponent(jLabel9)
                            .addComponent(jLabel8))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(dpFechaReg, javax.swing.GroupLayout.PREFERRED_SIZE, 210, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtNumPlan, javax.swing.GroupLayout.PREFERRED_SIZE, 210, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(cmbEstado, javax.swing.GroupLayout.PREFERRED_SIZE, 210, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                                .addComponent(jLabel11)
                                .addGap(44, 44, 44)
                                .addComponent(dpFechaI, javax.swing.GroupLayout.PREFERRED_SIZE, 210, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                                .addComponent(jLabel12)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(dpFechaF, javax.swing.GroupLayout.PREFERRED_SIZE, 210, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                        .addComponent(btnBuscar)
                        .addGap(18, 18, 18)
                        .addComponent(btnLimpiar)))
                .addGap(28, 28, 28))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel10)
                    .addComponent(txtNumPlan, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(dpFechaI, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel11))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(dpFechaReg, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel9)
                    .addComponent(dpFechaF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel12))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel8)
                    .addComponent(cmbEstado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnLimpiar)
                    .addComponent(btnBuscar))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        btnRegistrarEstimado.setText("Registrar a partir de Estimado");
        btnRegistrarEstimado.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRegistrarEstimadoActionPerformed(evt);
            }
        });

        btnRegistrarPedidos.setText("Registrar a partir de Pedidos");
        btnRegistrarPedidos.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRegistrarPedidosActionPerformed(evt);
            }
        });

        btnAnular.setText("Anular");
        btnAnular.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAnularActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(btnRegistrarEstimado)
                        .addGap(18, 18, 18)
                        .addComponent(btnRegistrarPedidos)
                        .addGap(18, 18, 18)
                        .addComponent(btnAnular))
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnRegistrarPedidos)
                    .addComponent(btnAnular)
                    .addComponent(btnRegistrarEstimado))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 230, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(108, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void btnRegistrarPedidosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRegistrarPedidosActionPerformed
        PlanVentasRegistrarJDialog planVentasDialog = new PlanVentasRegistrarJDialog(null, true);
        planVentasDialog.setParentPanel(this,1);
        planVentasDialog.setVisible(true);
    }//GEN-LAST:event_btnRegistrarPedidosActionPerformed

    private void btnAnularActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAnularActionPerformed
        if(tblPlanes.getSelectedRow()!=-1){
            int rowSel = tblPlanes.getSelectedRow();
            int confirma = JOptionPane.showConfirmDialog(this,"¿Desea anular el Plan de Ventas: "+planes.get(rowSel).getIdPlanVentas()+"?","Confirmar",2);
            if (JOptionPane.OK_OPTION==confirma){             
                GestionVentas.getInstance().anularPlanVentas(planes.get(rowSel).getIdPlanVentas());
                JOptionPane.showMessageDialog(this,"Se anuló correctamente el Plan de Ventas.");
                refreshItemsTable();
            }
        }
        else
            JOptionPane.showMessageDialog(this,"Debe seleccionar un registro de la tabla.");        
    }//GEN-LAST:event_btnAnularActionPerformed

    private void btnLimpiarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLimpiarActionPerformed
        limpiarCriterios();
    }//GEN-LAST:event_btnLimpiarActionPerformed

    private void tblPlanesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblPlanesMouseClicked
        if(evt.getClickCount()==2){
            int rowSel = tblPlanes.getSelectedRow();
            PlanVentasVerJDialog verDialog = new PlanVentasVerJDialog(null, true);
            verDialog.setPlanVentas(planes.get(rowSel));
            verDialog.setVisible(true);
        }
    }//GEN-LAST:event_tblPlanesMouseClicked

    private void btnBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBuscarActionPerformed
            long numero = (txtNumPlan.getText().equals(""))?0:Long.parseLong(txtNumPlan.getText());
            String estado;
            if(cmbEstado.getSelectedIndex()==1)
                estado = "Registrado";
            else if (cmbEstado.getSelectedIndex()==2)
                estado = "Procesado";
            else
                estado=null;
            Date fechaReg = (dpFechaReg.getDate()==null)?null:dpFechaReg.getDate();
            Date fechaI = (dpFechaI.getDate()==null)?null:dpFechaI.getDate();
            Date fechaF = (dpFechaF.getDate()==null)?null:dpFechaF.getDate();

            PlanVentas planVentas = new PlanVentas(null,numero,fechaReg,fechaI,fechaF,null,estado);
            ArrayList<PlanVentas> planesConsulta = GestionVentas.getInstance().queryPlanes(planVentas);
            refreshItemsTable2(planesConsulta);
    }//GEN-LAST:event_btnBuscarActionPerformed

    private void btnRegistrarEstimadoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRegistrarEstimadoActionPerformed
        PlanVentasRegistrarJDialog planVentasDialog = new PlanVentasRegistrarJDialog(null, true);
        planVentasDialog.setParentPanel(this,0);
        planVentasDialog.setVisible(true);
    }//GEN-LAST:event_btnRegistrarEstimadoActionPerformed

    private void dpFechaIActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_dpFechaIActionPerformed
        dpFechaF.setDate(null);
        dpFechaF.setEnabled(true);
        Calendar calendar = dpFechaF.getMonthView().getCalendar();
        calendar.setTime(dpFechaI.getDate());
        dpFechaF.getMonthView().setLowerBound(calendar.getTime());
    }//GEN-LAST:event_dpFechaIActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAnular;
    private javax.swing.JButton btnBuscar;
    private javax.swing.JButton btnLimpiar;
    private javax.swing.JButton btnRegistrarEstimado;
    private javax.swing.JButton btnRegistrarPedidos;
    private javax.swing.JComboBox cmbEstado;
    private org.jdesktop.swingx.JXDatePicker dpFechaF;
    private org.jdesktop.swingx.JXDatePicker dpFechaI;
    private org.jdesktop.swingx.JXDatePicker dpFechaReg;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable tblPlanes;
    private javax.swing.JTextField txtNumPlan;
    // End of variables declaration//GEN-END:variables
}
